package com.zhouyu.api;

import com.zhouyu.cons.JobConstans;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import lombok.extern.log4j.Log4j2;

/**
 * @Description:导入测试
 */
@Component
@Log4j2
public class ImportApi {
  @Autowired
  JobLauncher jobLauncher;

  @Autowired
  JobCenter jobCenter;

  /**
   * 简单的导入
   */
  public void runSimpleImport() {
    try {
      String dateParam = new Date().toString();
      JobParameters param = new JobParametersBuilder().addString("date", dateParam).toJobParameters();
      //执行job
      JobExecution execution = jobLauncher.run(jobCenter.importSimpleJob(JobConstans.IMPORT_SIMPLE_JOB), param);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 单个step使用线程池导入
   */
  public void importThreadPoolJob() {
    JobParameters param = new JobParametersBuilder().addString("date", new Date().toString()).toJobParameters();
    try {
      JobExecution execution = jobLauncher.run(jobCenter.importThreadJob(JobConstans.IMPORT_THREADPOOL_JOB), param);
      log.info("Exit Status :{} ", execution.getStatus());
    } catch (JobExecutionAlreadyRunningException e) {
      e.printStackTrace();
    } catch (JobRestartException e) {
      e.printStackTrace();
    } catch (JobInstanceAlreadyCompleteException e) {
      e.printStackTrace();
    } catch (JobParametersInvalidException e) {
      e.printStackTrace();
    }
  }

  /**
   * 导入数据库
   */
  public void importToDbJOb() {
    try {
      String dateParam = new Date().toString();
      JobParameters param = new JobParametersBuilder().addString("date", dateParam).toJobParameters();
      //执行job
      JobExecution execution = jobLauncher.run(jobCenter.importDbJob(JobConstans.IMPORT_DB_JOB), param);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
